local fmt = string.format

local function gen_criteria_args(criteria)
    local args = ""

    if criteria.app_id then
        args = args .. "-app-id " .. criteria.app_id .. " "
    end

    if criteria.app_title then
        args = args .. "-app-title " .. criteria.app_title .. " "
    end

    return args
end

local M = {}

function M.riverctl(args)
    print("riverctl " .. args)
    os.execute("riverctl " .. args)
end

function M.layout(name, cmd)
    M.riverctl("default-layout " .. name)
    os.execute(cmd .. " &")
end

function M.add_rule(criteria, rule)
    M.riverctl("rule-add " .. gen_criteria_args(criteria) .. rule)
end

function M.del_rule(criteria, rule)
    M.riverctl("rule-del " .. gen_criteria_args(criteria) .. rule)
end

function M.map(mode, keys, action)
    M.riverctl(fmt("map %s %s %s", mode, keys, action))
end

function M.map_pointer(mode, keys, action)
    M.riverctl(fmt("map-pointer %s %s %s", mode, keys, action))
end

function M.unmap(mode, keys)
    M.riverctl(fmt("unmap %s %s", mode, keys))
end

function M.maps(mode, keys)
    for k, v in pairs(keys) do
        M.map(mode, k, v)
    end
end

function M.keyboard_layout(locales, options)
    M.riverctl(fmt("keyboard-layout -options %s %s", options, locales))
end

function M.repeat_rate(rate, delay)
    M.riverctl(fmt("set-repeat %d %d", rate, delay))
end

function M.declare_mode(mode, keys)
    M.riverctl(fmt("declare-mode %s", mode))
    M.maps(mode, keys)
end

function M.appearance(theme)
    if theme.background_color then
        M.riverctl("background-color " .. theme.background_color)
    end

    if theme.border_color_focused then
        M.riverctl("border-color-focused " .. theme.border_color_focused)
    end

    if theme.border_color_unfocused then
        M.riverctl("border-color-unfocused " .. theme.border_color_unfocused)
    end
end

return M
